import axios from 'axios';
import { message } from 'ant-design-vue';
import qs from 'qs';
import store from '@/store';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000 // 请求超时时间
});

//请求
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['API-User-Token'] = store.getters.token;
  }
  return config;
});

//响应
service.interceptors.response.use(response => {
  const data = response.data;

  if (response.config.url.indexOf('/hydrobim/damInfo/exportDamStatistics') > -1 || response.config.url.indexOf('/hydrobim/damInfo/exportDamInfo') > -1) {
    return Promise.resolve(response);
  }
  if (data.code === 0) {
    return Promise.resolve(response);
  } else {
    message.error(response.data.message || '');
    return Promise.reject(response);
  }
});

let http = {};

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

http.get = function(url, params = null) {
  return new Promise((resolve, reject) => {
    service
      .get(url, { params })
      .then(res => {
        resolve(res.data);
      })
      .catch(e => {
        reject(e);
      });
  });
};

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

http.post = function(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url, JSON.stringify(params), {
        headers: {
            'Content-Type': 'application/json'
        },
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(e => {
        reject(e);
      });
  });
};

http.getBlob = function(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url, JSON.stringify(params), {
        headers: {
            'Content-Type': 'application/json'
        },
        responseType: 'arraybuffer'
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(e => {
        reject(e);
      });
  });
};

http.put = function(url, params) {
  return new Promise((resolve, reject) => {
    service
      .put(url, JSON.stringify(params), {
        headers: {
            'Content-Type': 'application/json'
          }
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(e => {
        reject(e);
      });
  });
};

export default http;
